package net.sashag.nadlandroid;

import android.content.Intent;
import android.content.res.Configuration;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.apps.analytics.easytracking.EasyTracker;
import com.google.android.apps.analytics.easytracking.TrackedActivity;
import com.googlecode.androidannotations.annotations.AfterViews;
import com.googlecode.androidannotations.annotations.Bean;
import com.googlecode.androidannotations.annotations.EActivity;
import com.googlecode.androidannotations.annotations.OptionsItem;
import com.googlecode.androidannotations.annotations.OptionsMenu;
import com.googlecode.androidannotations.annotations.ViewById;
import com.parse.ParseAnonymousUtils;
import com.parse.ParseUser;
import com.parse.PushService;

@EActivity(R.layout.main)
@OptionsMenu(R.menu.main_menu)
public class NadlandroidActivity extends TrackedActivity {

	private static final int RC_SIGNUP = 1;
	
	@Bean protected FavoritesManager favoritesManager;
	@Bean protected RegionSubscribeDialog regionSubscribeDialog;
	@Bean protected ListingManagementDialog listingManagementDialog;
	
	@ViewById protected TextView txtNaggingBanner;
	@ViewById protected GridView grdNavigation;
	
	private boolean isUserLoggedIn;
	private NavigationButtonGridAdapter navigationAdapter;
	
	private NavigationGridItem[] alwaysOnItems = {
		new NavigationGridItem("Custom Search", R.drawable.customsearch, new Runnable() { public void run() {onApartmentCustomSearchClicked();} }),
		new NavigationGridItem("Around Me", R.drawable.locationsearch, new Runnable() { public void run() {onApartmentSearchAroundMeClicked();} })
	};
	private NavigationGridItem[] loggedInItems = {
		new NavigationGridItem("Favorites", R.drawable.favorites, new Runnable() { public void run() {onViewFavoritesClicked();} }),
		new NavigationGridItem("Messages", R.drawable.messages, new Runnable() { public void run() {onMessagesClicked();} }),
		new NavigationGridItem("Submit Listing", R.drawable.submitlisting, new Runnable() { public void run() {onSubmitListingClicked();} }),
		new NavigationGridItem("Manage Listings", R.drawable.managelistings, new Runnable() { public void run() {onManageListingsClicked();} }),
		new NavigationGridItem("Subscribe", R.drawable.subscribe, new Runnable() { public void run() {onSubscribeClicked();} })	
	};
	private NavigationGridItem[] loggedOutItems = {
		new NavigationGridItem("Register", R.drawable.register, new Runnable() { public void run() {onRegisterClicked();} })
	};

	@AfterViews
	protected void initialSetup() {
		navigationAdapter = new NavigationButtonGridAdapter(this);
		for (NavigationGridItem item : alwaysOnItems) {
			navigationAdapter.addButton(item);
		}
		grdNavigation.setAdapter(navigationAdapter);
		switch (getResources().getConfiguration().orientation) {
		case Configuration.ORIENTATION_LANDSCAPE:
			grdNavigation.setNumColumns(3);
			break;
		case Configuration.ORIENTATION_PORTRAIT:
			grdNavigation.setNumColumns(2);
			break;
		}
		
		ParseUser currentUser = ParseUser.getCurrentUser();
		setLoggedInFunctionality(!ParseAnonymousUtils.isLinked(currentUser));
		PushService.subscribe(this, "TestChannel", NadlandroidActivity.class);
		PreferenceManager.setDefaultValues(this, R.xml.preferences, false /*only if never called before*/);
		favoritesManager.setProximityAlertsFromFavoriteApartments(currentUser);
	}

	private void setLoggedInFunctionality(boolean loggedIn) {
		isUserLoggedIn = loggedIn;
		if (isUserLoggedIn) {
			for (NavigationGridItem item : loggedInItems) {
				navigationAdapter.addButton(item);
			}
			for (NavigationGridItem item : loggedOutItems) {
				navigationAdapter.removeButton(item.text);
			}
			txtNaggingBanner.setVisibility(View.GONE);
			String currentUserName = ParseUser.getCurrentUser().getString("Fullname");
			if (currentUserName == null) {
				currentUserName = ParseUser.getCurrentUser().getUsername();
			}
			if (currentUserName != null) {
				setTitle("Welcome, " + currentUserName + "!");
			}
		} else {
			for (NavigationGridItem item : loggedOutItems) {
				navigationAdapter.addButton(item);
			}
			for (NavigationGridItem item : loggedInItems) {
				navigationAdapter.removeButton(item.text);
			}
			txtNaggingBanner.setVisibility(View.VISIBLE);
			setTitle("Nadlandroid");
		}
	}
	
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		MenuItem logoutItem = menu.findItem(R.id.menuLogout);
		logoutItem.setEnabled(isUserLoggedIn);
		return super.onPrepareOptionsMenu(menu);
	}
	
	@OptionsItem(R.id.menuLogout)
	protected void onMenuLogoutClicked() {
		ParseUser.logOut();
		setLoggedInFunctionality(false);
	}
	
	@OptionsItem(R.id.menuSettings)
	protected void onMenuSettingsClicked() {
		new NadlandroidPreferencesActivity_.IntentBuilder_(this).start();
	}
		
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case RC_SIGNUP:
			if (resultCode == RESULT_OK) {
				setLoggedInFunctionality(true);
				Toast.makeText(this, "Welcome, " + data.getStringExtra("Fullname"), Toast.LENGTH_LONG).show();
			}
			break;
		default:
			break;
		}
	}
	
	private void onRegisterClicked() {
		startActivityForResult(new Intent(this, SignupActivity_.class), RC_SIGNUP);
	}

	private void onApartmentCustomSearchClicked() {
		new ApartmentListingActivity_.IntentBuilder_(this).searchAroundMe(false).start();
	}
	
	private void onApartmentSearchAroundMeClicked() {
		new ApartmentListingActivity_.IntentBuilder_(this).searchAroundMe(true).start();
	}
	
	private void onSubmitListingClicked() {
		new SubmitListingActivity_.IntentBuilder_(this).start();
	}
	
	private void onMessagesClicked() {
		new MessagesActivity_.IntentBuilder_(this).start();
	}
	
	private void onViewFavoritesClicked() {
		String[] favorites = favoritesManager.getFavoriteApartmentIds(ParseUser.getCurrentUser());
		if (favorites == null || favorites.length == 0) {
			Toast.makeText(this, "You don't have any favorites yet", Toast.LENGTH_LONG).show();
			return;
		}
		EasyTracker.getTracker().trackPageView("Favorites");
		new GridApartmentListingActivity_.IntentBuilder_(this)
			.title("Your Favorites")
			.apartmentIds(favorites)
			.isShowingFavorites(true)
			.start();
	}
	
	private void onSubscribeClicked() {
		regionSubscribeDialog.show();
		EasyTracker.getTracker().trackPageView("Region Subscriptions");
	}
	
	private void onManageListingsClicked() {
		listingManagementDialog.show();
		EasyTracker.getTracker().trackPageView("Manage Listings");
	}
	
}